package cn.kenny.resource.controller;

import cn.kenny.resource.constant.MessageConstant;
import cn.kenny.resource.entity.PageResult;
import cn.kenny.resource.entity.Result;
import cn.kenny.resource.mapper.SubjectMapper;
import cn.kenny.resource.pojo.*;
import cn.kenny.resource.service.UserService;
import cn.kenny.resource.utils.QiniuUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.ws.rs.core.Response;
import java.util.*;

@RestController
@RequestMapping("/user")
@CrossOrigin(originPatterns = "*", methods = {RequestMethod.GET, RequestMethod.POST})
public class UserController {

    //七牛云外链
    private String url = "http://r087ahtxp.hn-bkt.clouddn.com/";

    @Autowired
    private UserService userService;

    @Autowired
    private SubjectMapper subjectMapper;

    @RequestMapping("hello")
    public String hello(){
        return "hello tencent";
    }

    @RequestMapping("login")
    public Result login(@RequestParam("telphone")String telphone,
                        @RequestParam("password")String password,
                        @RequestParam("utype")Integer utype){
        User user = new User();
        user.setTelphone(telphone);
        user.setPassword(password);
        user.setUtype(utype);
        User login = userService.login(user);
        if(login == null){
            return new Result(false,MessageConstant.LOGIN_FAIL);
        }
        return new Result(true, MessageConstant.LOGIN_SUCCESS,login);
    }

    @RequestMapping("register")
    public Result register(@RequestParam("telphone")String tel,
                           @RequestParam("username")String username,
                           @RequestParam("password")String password){
        User user = new User();
        user.setTelphone(tel);
        user.setUsername(username);
        user.setPassword(password);
        try {
            userService.register(user);
            return new Result(true, MessageConstant.REGISTER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.REGISTER_FAIL);
        }
    }

    @RequestMapping("getuser")
    public Result getUserInfo(Integer id){
        User user = userService.findById(id);
        if (user != null)
            return  new Result(true, MessageConstant.QUERY_USER_SUCCESS,user);
        return new Result(false, MessageConstant.QUERY_USER_FAIL);
    }

    @RequestMapping("myfilelist")
    public Result getUserFileList(Integer id){
        PageResult pageResult = userService.findDocByUserId(id);
        if(pageResult.getRows() != null && pageResult.getRows().size() > 0){
            return new Result(true, MessageConstant.QUERY_USERDOCUMENTLIST_SUCCESS,pageResult);
        }
        return new Result(false, MessageConstant.QUERY_USERDOCUMENTLIST_FAIL,pageResult);
    }

    @RequestMapping("subjectfiles")
    public Result getSubjectFileList(Integer sname){
        PageResult pageResult = userService.findDocBySubjectId(sname);
        if(pageResult.getRows() != null && pageResult.getRows().size() > 0){
            return new Result(true, MessageConstant.QUERY_SUBJECTDOCUMENTLIST_SUCCESS,pageResult);
        }
        return new Result(false, MessageConstant.QUERY_SUBJECTDOCUMENTLIST_FAIL);
    }

    @RequestMapping("subjects")
    public Result getSubjects(){
        try {
            List<Integer> parentList = subjectMapper.getParentList();

            Map<String, List<Subject>> map = new HashMap<String, List<Subject>>();
            for(Integer a:parentList){
                String temp = subjectMapper.getParent(a);
                List<Subject> list = subjectMapper.getSubjectByParent(a);
                map.put(temp,list);
            }
            return new Result(true, MessageConstant.QUERY_SUBJECTLIST_SUCCESS,map);
        } catch (Exception e) {
            return new Result(false,MessageConstant.QUERY_SUBJECTLIST_FAIL);
        }
    }

    @RequestMapping("upload")
    public Result upload(@RequestParam("uid")Integer uid,@RequestParam("sid") Integer sid,
                         @RequestParam("resource")MultipartFile resource){
        try{
            //获取原始文件名
            String originalFilename = resource.getOriginalFilename();
            //获取文件size
            long size = resource.getSize();

            int lastIndexOf = originalFilename.lastIndexOf(".");
            //获取文件后缀
            String suffix = originalFilename.substring(lastIndexOf);
            //使用UUID随机产生文件名称，防止同名文件覆盖
            String fileName = UUID.randomUUID().toString() + suffix;
            QiniuUtils.upload2Qiniu(resource.getBytes(),fileName);
            //图片上传成功
            Result result = new Result(true, MessageConstant.UPLOAD_SUCCESS);
            result.setData(fileName);
            //将上传图片名称存入文件表
//            jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_RESOURCES,fileName);
            Doc doc = new Doc();
            doc.setName(fileName);
            doc.setSize(size);
            doc.setCtime(new Date());
            doc.setUid(uid);
            doc.setSid(sid);
            doc.setPath(url + fileName);
            doc.setDname(originalFilename);
            doc.setDsize((size / 1024) + "K");
            userService.addDoc(doc);
            return result;
        }catch (Exception e){
            e.printStackTrace();
            //图片上传失败
            return new Result(false,MessageConstant.UPLOAD_FAIL);
        }
    }

    @RequestMapping("deldoc")
    public Result deleteDocument(Integer id){
        //1、调用服务层获取文件信息
        Doc doc = userService.findDocById(id);
        //2、使用工具类删除七牛云上的文件
        String docName = doc.getName();
        QiniuUtils.deleteFileFromQiniu(docName);
        //3、删除数据库中的文件信息
        Integer num = userService.delDocById(id);
        if(num > 0 )
            return new Result(true,MessageConstant.DELETE_DOCUMENT_SUCCESS);
        return new Result(false,MessageConstant.DELETE_DOCUMENT_FAIL);
    }

    @RequestMapping("oneword")
    public Result getWord(){
        List<Word> wordList = userService.getWord();
        if(wordList != null && wordList.size() > 0){
            return new Result(true,MessageConstant.QUERY_WORDLIST_SUCCESS,wordList);
        }
        return new Result(false,MessageConstant.QUERY_WORDLIST_FAIL);
    }

    @RequestMapping("question")
    public Result getQuestion(){
        Question question = userService.getQuestion();
        if(question != null)
            return new Result(true,MessageConstant.QUERY_QUESTION_SUCCESS,question);
        return new Result(false,MessageConstant.QUERY_QUESTION_FAIL);
    }
}
